<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instruction.fundAccountCode" @change="handleChange($event, 'fundAccountCode')" size="mini">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.stockCode"
                            @change="handleChange($event, 'stockCode')"
                            @visible-change="handleStockVisibleChange"
                            filterable
                            remote
                            :remote-method="getstockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="handleClearStock"
                        >
                            <el-option v-for="i in stockReport" :key="i.stockCode" :label="i.stockCode + ' ' + i.stockNameSt" :value="i.stockCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businClass" size="mini" @change="handleChange($event, 'businClass')">
                            <el-option v-for="i in defaultStockBusinessTypes" :key="i.value" :label="i.value + ' ' + i.label" :value="i.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select
                            v-model="instruction.orderDirection"
                            size="mini"
                            :class="['font-color-' + textColor]"
                            @change="handleChange($event, 'orderDirection')"
                        >
                            <el-option
                                v-for="i in orderDirectionData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="交易对手:" v-if="isBatchFund">
                        <el-select
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            @change="handleChange($event, 'opponentCode')"
                            clearable
                            filterable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option v-for="i in opponentReport" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="期限:">
                        <el-select v-model="instruction.deadline" size="small" @change="handleChange($event, 'deadline')">
                            <el-option v-for="item in deadlineSelectData" :key="item.dicKey" :label="item.dicKeyName" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="费率:" style="margin-top:3px">
                        <RiskInputNumber
                            :input="instruction.rate"
                            :inputAfter="'%'"
                            :precision="2"
                            :maxlength="15"
                            :field="'rate'"
                            :disabled="true"
                            @getInputNumber="getInputNumber(arguments)"
                            :colorStyle="textColor"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="融出数量:">
                        <RiskInputNumber
                            :input="instruction.orderAmount"
                            :inputAfter="'股'"
                            :field="'orderAmount'"
                            :maxlength="15"
                            :precision="2"
                            :colorStyle="textColor"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="交易对手:" v-if="isBatchStock">
                        <el-select
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            @change="handleChange($event, 'opponentCode')"
                            clearable
                            filterable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option v-for="i in opponentReport" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { handleTextColor } from '@/utils/tools';

@Component({
    name: 'RefinancingForm',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})

// 交易所指令
export default class RefinancingForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    stockInfoCache: any;
    @Prop()
    renderCount: number;
    @Prop()
    notMesh: boolean; // 非风险试算页面
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多证券指令
    Invest: any = new Invest();
    handleTextColor = handleTextColor;

    stockReport: any[] = []; // 证券代码下拉
    deadlineSelectData: any[] = [
        {
            dicKey: '1',
            dicKeyName: '3天',
            value: '3',
        },
        {
            dicKey: '2',
            dicKeyName: '7天',
            value: '7',
        },
        {
            dicKey: '3',
            dicKeyName: '14天',
            value: '14',
        },
        {
            dicKey: '4',
            dicKeyName: '28天',
            value: '28',
        },
        {
            dicKey: '5',
            dicKeyName: '182天',
            value: '182',
        },
    ]; // 期限下拉数据

    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    stockInfo: any = {}; // 选择证券信息
    textColor: string = ''; // 文本颜色
    opponentReportState: boolean = false;
    opponentReport: any[] = []; // 发行人下拉
    // 基础查询条件
    instruction: any = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        marketCode: '',
        orderDirection: 'l', // 委托方向
        stockCode: '',
        fundNameSt: '',
        fundAccountName: '',
        businClass: '1', // 业务类型
        deadline: '', // 期限
        rate: '', // 费率
        orderAmount: '', // 融出数量
        opponentCode: '', // 交易对手
        lastPriceOrorderPrice: '',
    };
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    // 委托方向数据
    orderDirectionData: any[] = [
        {
            dictKey: 'l',
            dictKeyName: '证券转融通融出',
        },
        {
            dictKey: '98',
            dictKeyName: '转融通提前了结',
        },
    ];

    orderDirectionPojo: any = {
        l: '证券转融通融出',
        '98': '转融通提前了结',
    };
    // 业务类型
    defaultStockBusinessTypes: SelectOptionItemData[] = [
        {
            label: '交易所业务',
            value: '1',
        },
    ];

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            instruction.businClass = instruction.businessType;
            await this.getstockCodeList(this.instruction.stockCode);
            this.stockInfo = this.stockReport.find(item => item.stockCode === instruction.stockCode);
            instruction.marketCode = this.stockInfo?.marketCode;
            console.log(this.stockInfo, instruction.marketCode, ' instruction.marketCode');

            this.instruction = JSON.parse(JSON.stringify(instruction));
            console.log(this.instruction, 'this.detail');
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction.orderDirection', { immediate: true, deep: true })
    handleFieldColor() {
        if (['l'].includes(this.instruction.orderDirection)) {
            this.textColor = 'green';
        } else {
            this.textColor = 'red';
        }
    }

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        this.getOpponentCode('');
        this.changeSelect(false);
    }

    // 更改交易对手方选择框样式
    changeSelect(state: boolean) {
        let obj = document.getElementById('multiAndSearch').parentNode.querySelector('.el-select__caret');
        obj.classList.add('el-icon-arrow-up');
        if (state) {
            obj.classList.add('is-reverse');
        } else {
            obj.classList.remove('is-reverse');
        }
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        return this.fundAccountCodeSelectData[this.instruction.fundCode] || [];
    }

    // 参数变动
    async handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'fundAccountCode') {
            this.handleFundAccountCodeChange(value);
        } else if (field === 'stockCode') {
            await this.handleStockCodeChange(value);
        } else if (field === 'deadline') {
            await this.getrefinancingRate(value, 1);
        }
        this.$emit('handleSettingValue', { ...this.instruction }, '14');
    }

    // 产品代码回调
    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleChange(val, 'fundCode');
    }

    // 输入框
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        this.handleChange(value, field);
    }

    // 产品代码改变
    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    // 组合编码改变
    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/stock/report/select/8', {
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockReport = res;
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    // 证券代码选择变动事件
    async handleStockCodeChange(value: string) {
        this.instruction.reportCode = '';
        this.instruction.marketCode = '';
        if (value) {
            this.stockInfo = this.stockReport.find(item => item.stockCode === value);
            this.$emit('getStockInfo', this.stockInfo);
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.marketCode = this.stockInfo.marketCode;
            this.instruction.stockCode = this.stockInfo.stockCode;
            await this.getPrice(this.stockInfo.stockCode);
        }
    }

    getPrice(stockCode: string) {
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/dataEngine/getStockPrice/' + stockCode)
                .then((result: any) => {
                    this.instruction.lastPriceOrorderPrice = result.toString();
                    resolve(result);
                })
                .catch(err => {
                    this.instruction.lastPriceOrorderPrice = '';
                    reject(err);
                });
        });
    }

    // 证券代码清除事件
    handleClearStock() {
        this.getstockCodeList('');
        this.stockInfo = null;
    }

    handleStockVisibleChange(val) {
        if (!this.instruction.stockCode && val && !this.stockReport.length) {
            this.getstockCodeList('');
        }
    }

    // 获取交易对手方信息
    private getOpponentCode(value: string) {
        this.opponentReportState = true;
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentReport = res;
                this.opponentReportState = false;
            })
            .catch(() => {
                this.opponentReportState = false;
            });
    }

    // 获取转融通费率
    getrefinancingRate(term, type) {
        this.$axios
            .post('/dict/query/refinancingRate', {
                term,
                type,
            })
            .then((res: any) => {
                this.instruction.rate = res.borrowRate * 100;
            })
            .catch(() => {});
    }

    /**
     * 重置表单数据
     */
    resetValues() {
        this.instruction.reportCode = '';
        this.instruction = {
            ...this.instruction,
            // 转融通指令额外表单数据
            deadline: '', // 期限
            rate: '', // 费率
            orderAmount: '', // 融出数量
            opponentCode: '', // 交易对手
        };
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
